package com.cropflow.service;

import com.cropflow.entity.MaintenanceRecord;
import com.cropflow.repository.MaintenanceRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MaintenanceService {
    
    @Autowired
    private MaintenanceRecordRepository maintenanceRecordRepository;
    
    public List<MaintenanceRecord> getAllMaintenanceRecords() {
        return maintenanceRecordRepository.findAll();
    }
    
    public List<MaintenanceRecord> getMaintenanceRecordsByVehicleId(Long vehicleId) {
        return maintenanceRecordRepository.findByVehicleId(vehicleId);
    }
    
    public MaintenanceRecord saveMaintenanceRecord(MaintenanceRecord record) {
        if (record.getScheduledDate() == null) {
            record.setScheduledDate(LocalDateTime.now());
        }
        if (record.getStatus() == null) {
            record.setStatus(MaintenanceRecord.MaintenanceStatus.SCHEDULED);
        }
        return maintenanceRecordRepository.save(record);
    }
    
    public void deleteMaintenanceRecord(Long id) {
        maintenanceRecordRepository.deleteById(id);
    }
    
    public List<MaintenanceRecord> getScheduledMaintenance(LocalDateTime start, LocalDateTime end) {
        return maintenanceRecordRepository.findByScheduledDateBetween(start, end);
    }
    
    public List<MaintenanceRecord> getMaintenanceByStatus(MaintenanceRecord.MaintenanceStatus status) {
        return maintenanceRecordRepository.findByStatus(status);
    }
}